#!/usr/bin/python

import json, sys, os, subprocess, urllib, shutil, hashlib

api_root = 'https://secure.etvnet.com/api/v3.0/'
f = open(os.environ['HOME'] + '/.etvcc/token.txt')
access_token = f.readline().strip()
f.close()

def read_json(fname):
    f = open(fname)
    text = f.read()
    f.close()
    a = json.loads(text)
    return a

def get_cached(url, name):
    md5 = hashlib.md5(url).hexdigest()
    fname = name + '-' + md5 + '.txt'
    if not os.path.exists(fname):
        print 'loading %s: %s' % (name, url)
        (tmpname, headers) = urllib.urlretrieve(url)
        shutil.move(tmpname, fname)
    a = read_json(fname)
    return a

def get_favorites():
    url = api_root + 'video/bookmarks/folders.json?per_page=10&access_token=%s' % access_token
    a = get_cached(url, 'folders')
    return a['data']['folders']

def get_bookmarks(folder_id):
    url = api_root + 'video/bookmarks/folders/%d/items.json?per_page=10&access_token=%s' % (folder_id, access_token)
    a = get_cached(url, 'folders')
    return a['data']['bookmarks']

def get_children(child_id):
    url = api_root + '/video/media/%d/children.json?per_page=10&access_token=%s' % (child_id, access_token)
    a = get_cached(url, 'children')
    return a['data']['children']

def get_stream_url(object_id):
    url = api_root + 'video/media/%d/watch.json?access_token=%s&format=mp4&protocol=hls&bitrate=800' % (object_id, access_token)
    a = get_cached(url, 'stream')
    return a['data']['url']

def print_list(list):
    print ' 0 ..'
    idx = 1
    for item in list:
        if 'title' in item:
            print '%2s %-30s' % (idx, item['title'])
        else:
            print '%2d %-30s %s' % (idx, item['short_name'][:30], item['on_air'])
        idx += 1

def print_location(stack):
    for item in stack:
        print item[0] + ' ::',
    print '> ',

stack = [ ['favorites', 'favorites', get_favorites()] ]

while True:
    print '\x1b[2J'
    print '============================================================='
    print_list(stack[-1][2])
    print '============================================================='
    print_location(stack)

    cmd = sys.stdin.readline().strip()
    if cmd == '':
        continue

    state = stack[-1][1]
    children = stack[-1][2]
    idx = int(cmd) - 1
    if idx == -1:
        stack.pop()
        if len(stack) == 0:
            break
        continue
    if idx >= len(children):
        continue

    child = children[idx]
    id = child['id']

    if state == 'favorites':
        stack.append([child['title'], 'bookmarks', get_bookmarks(id)])
    elif state == 'bookmarks':
        stack.append([child['short_name'], 'children', get_children(id)])
    elif state == 'children':
        if child['type'] == 'Container':
            stack.append([child['short_name'], 'children', get_children(id)])
        else:
            url = get_stream_url(id)
            p = subprocess.Popen(['/cygdrive/c/apps/ffmpeg/ffplay', url])
            print 'player:', p.wait()
